const config=require('./config')
const common=require('./common');
const requestHandle=(response)=>{
  return new Promise((resolve, reject)=>{
    if(response?.code=="INVOKE_FUNCTION_FAILED"){
      wx.showModal({
        title:'错误',
        content:"调用服务出错"+response?.message,
        showCancel:false
      })
      reject({})
    }
    if(response?.errorCode){
      common.showErrorMsg(response)
      // wx.showModal({
      //   title:'错误',
      //   content:response.errorMsg,
      //   showCancel:false
      // })
      reject({errorMsg:response.errorMsg,errorCode:response.errorCode})
    }else{
      resolve(response);
    }
  })
}
const loginRequest=async(func,action,data)=>{
  wx.showLoading({
    title: '载入中',
  })
  try{
    const response=await new Promise((resolve, reject)=>{
      wx.request({
        url: config.baseUrl+func+"/"+action,
        data:{
          ...data
        },
        success:(res)=>{
          if(res.statusCode==200){
            resolve(res.data)
          }else{
            reject(common.error("用户登录失败",-1))
          }
        },
        fail:(res)=>{
          console.error("请检查网络",res)
          reject(common.error("请检查网络",-1))
        },
        complete:(res)=>{
          wx.hideLoading({
          })
        }
      })
    })
    return requestHandle(response)
  }catch(err){
    console.error("loginRequest error",err)
    return Promise.reject(err)    
  }
}
module.exports = {
  requestHandle,
  loginRequest
}
    